<template>
    <div>
        <el-card>
            <el-form :inline="true" :model="query" class="query-form" size="small">
                <el-form-item class="query-form-item">
                    <el-input v-model="query.attributesname" placeholder="请输入商品属性模板名称" prefix-icon="el-icon-search"
                              clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-refresh" @click="onRest"></el-button>
                    <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
                    <el-button type="primary" icon="el-icon-edit" @click.native="add('添加', null, null)">新增</el-button>
                </el-form-item>
            </el-form>
            <el-table ref="multipleTable" v-loading="listLoading" :data="list"
                      :header-cell-style="{ background: '#F4F4F5', color: '#606266' }" border>
                <el-table-column label="商品属性模板 ID" prop="attributesid" align="center"/>
                <el-table-column label="商品属性模板名称" prop="attributesname" align="center"/>
                <el-table-column label="创建时间" align="center" width="180" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <i class="el-icon-time" v-if="scope.row.createtime!=null"></i>
                        <span v-if="scope.row.createtime!=null">{{ scope.row.createtime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                        <span v-else>无</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click.native="add('编辑', scope.$index, scope.row)">编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                class="pagination-container"
                background
                :page-size="query.pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total,sizes,prev, pager, next, jumper"
                :current-page="this.query.currentPage"
                :page-sizes="[5,10, 20, 30, 50]"
                :total="totalNumber"
            ></el-pagination>
            <el-dialog
                :title="title"
                :visible.sync="dialogVisible"
                width="50%"
                :before-close="handleClose"
                :close-on-click-modal="false">
                <template slot="title">
                    <div class="avue-crud__dialog__header">
                        <span class="el-dialog__title">
                            <span
                                style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>{{title}}</span>
                    </div>
                </template>
                <el-card>

                    <el-form :inline="true" :model="rowData" ref="formRef" class="query-form" size="small">
                      <el-form-item prop="attributesname" :rules="{required: true, message: '模板名称不能为空', trigger: 'blur'}">
                        <el-input v-model.trim="rowData.attributesname" placeholder="请输入属性模板名称" clearable></el-input>
                      </el-form-item>
                      <div class="el-title">基本属性</div>
                        <div v-for="(item, index) in rowData.templateItemList"
                             :key="index">
                            <el-form-item :rules="{required: true, message: '属性名称不能为空', trigger: 'blur'}" :prop="'templateItemList.' + index + '.fieldname'">
                                <el-input placeholder="请输入属性项名称" v-model.trim="item.fieldname"></el-input>
                            </el-form-item>
                            <el-form-item :rules="{required: true, message: '属性类型不能为空', trigger: 'change'}" :prop="'templateItemList.' + index + '.fieldtype'">
                                <el-select style="width: 115px" v-model="item.fieldtype">
                                    <el-option label="数字" value="数字"></el-option>
                                    <el-option label="文字" value="文字"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-select style="width: 115px" v-model="item.ismust">
                                    <el-option :label="'必填'" :value="0"></el-option>
                                    <el-option :label="'非必填'" :value="1"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="addBaseAttr(index)" class="setBtn" type="primary"
                                    icon="el-icon-plus" plain size="mini">
                                </el-button>
                                <el-button @click="delBaseAttr(index)" class="setBtn" type="danger"
                                    icon="el-icon-minus" plain size="mini">
                                </el-button>
                            </el-form-item>
                        </div>
                      <div class="el-title">扩展属性</div>
                        <div v-for="(item, index) in rowData.extendItemList" :key="'ex' + index">
                            <el-form-item :rules="{required: true, message: '属性名称不能为空', trigger: 'blur'}" :prop="'extendItemList.' + index + '.extendfieldname'">
                                <el-input placeholder="请输入属性项名称" v-model.trim="item.extendfieldname"></el-input>
                            </el-form-item>
                            <el-form-item :rules="{required: true, message: '属性类型不能为空', trigger: 'change'}" :prop="'extendItemList.' + index + '.fieldtype'">
                                <el-select style="width: 115px" v-model="item.fieldtype">
                                    <el-option :label="'数字'" :value="'数字'"></el-option>
                                    <el-option :label="'文字'" :value="'文字'"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-select style="width: 115px" v-model="item.ismust">
                                    <el-option :label="'必填'" :value="0"></el-option>
                                    <el-option :label="'非必填'" :value="1"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="addExtendAttr(index)" class="setBtn" type="primary"
                                    icon="el-icon-plus" plain size="mini"></el-button>
                                <el-button @click="delExtendAttr(index)" class="setBtn" type="danger"
                                    icon="el-icon-minus" plain size="mini"></el-button>
                            </el-form-item>
                        </div>
                    </el-form>
                </el-card>
                <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="submitTemplate">确 定</el-button>
      </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    import {
        addOrUpdateAttributesTemplate,
        queryAttributesTemplateList
    } from "../../api/classification/classification.js";

    const templateFromList = {
        attributesid: '',
        attributesname: "", // 模板名称
        templateItemList: [
            {
                fieldname: "", // 基本属性名称
                fieldtype: null, // 模板类型
                ismust: 0, // 1必填 0非必填
            },
        ],
        extendItemList: [
            {
                extendfieldname: '',// 扩展属性名称
                fieldtype: null, // 模板类型
                ismust: 0, // 1必填 0非必填
            },
        ]
    }
    export default {
        data() {
            return {
                listLoading: false,
                submitJson: templateFromList, // 添加 编辑的数据
                title: "新增",
                dialogVisible: false, // 判断弹框是否显示
                list: [],
                query: {
                    attributesname: "",
                    currentPage: 1,
                    pageSize: 5
                },
                rowData:{},
                totalNumber: 0,
                loading: false,
            };
        },
        methods: {
            // 点击添加
            addBaseAttr(index) {
                this.rowData.templateItemList.splice(index + 1, 0, {
                    fieldname: "", // 模板名字
                    fieldtype: null, // 模板类型
                    fieldvalue: null, // 这个不用管
                    ismust: 0, // 1必填 0非必填
                });
            },
            // 点击删除
            delBaseAttr(index) {
                if (this.rowData.templateItemList.length > 1) {
                    this.rowData.templateItemList.splice(index, 1);
                }
            },
            addExtendAttr(index) {
                this.rowData.extendItemList.splice(index + 1, 0, {
                    fieldname: "", // 模板名字
                    fieldtype: null, // 模板类型
                    fieldvalue: null, // 这个不用管
                    ismust: 0, // 1必填 0非必填
                });
            },
            delExtendAttr(index) {
                if (this.rowData.extendItemList.length > 1) {
                    this.rowData.extendItemList.splice(index, 1);
                }
            },
            // 确定提交模板
            submitTemplate() {
                // if (!this.rowData.attributesname) {
                //     this.$message.error('模板名称不能为空');
                //     return
                // }
                // this.rowData.templateItemList.forEach((el, index) => {
                //     if (!el.fieldname) {
                //         this.$message.error('属性名称不能为空')
                //         throw new Error()
                //     }
                //     if (el.fieldname.length > 10) {
                //         this.$message.error('属性名称不能大于10个字符')
                //         throw new Error()
                //     }
                //     if (!el.fieldtype) {
                //         this.$message.error('模板类型不能为空')
                //         throw new Error()
                //     }
                // })
                // this.rowData.extendItemList.forEach((el, index) => {
                //     if (!el.extendfieldname) {
                //         this.$message.error('扩展属性名称不能为空')
                //         throw new Error()
                //     }
                //     if (el.extendfieldname.length > 10) {
                //         this.$message.error('扩展属性名称不能大于10个字符')
                //         throw new Error()
                //     }
                //     if (!el.fieldtype) {
                //         this.$message.error('模板类型不能为空')
                //         throw new Error()
                //     }
                // })
              this.$refs['formRef'].validate((valid) => {
                if (valid) {
                  let v = this.rowData
                  let params = {
                    attributesname: v.attributesname,
                    extendItemList: v.extendItemList,
                    templateItemList: v.templateItemList
                  }
                  if (this.title === '编辑') {
                    params.attributesid = v.attributesid
                  }
                  console.log(params)
                  this.loading = true
                  addOrUpdateAttributesTemplate(params).then((res) => {
                    if (res.code === 0) {
                      this.$message.success('提交成功')
                      this.dialogVisible = false
                      this.submitJson = templateFromList
                      this.getList()
                      setTimeout(() => {
                        this.loading = false
                      }, 0.3 * 1000)
                    } else {
                      setTimeout(() => {
                        this.loading = false
                      }, 0.3 * 1000)
                      this.$message.error(res.message)
                    }
                  })
                    .catch((res) => {
                      this.$message.error(res.message);
                      this.loading = false;
                    })
                }
              })

            },
            // 关闭弹框
            handleClose() {
                this.dialogVisible = false;
                this.submitJson = templateFromList
              this.$refs['formRef'].clearValidate()
            },
            onRest() {
                this.query = {
                    username: "",
                    status: "",
                    currentPage: 1,
                    pageSize: 10,
                    templateType: 4,
                    roleId: "",
                };
                this.getList();
            },
            // 搜索查询
            onSearch() {
                this.query.currentPage = 1;
                this.getList()
            },
            // 新增 编辑
            add(title, index, row) {
                this.title = title;
                if (title === '编辑') {
                    this.rowData = JSON.parse(JSON.stringify(row))
                }else{
                    this.rowData = {
                        attributesid: '',
                        attributesname: "", // 模板名称
                        templateItemList: [
                            {
                                fieldname: "", // 基本属性名称
                                fieldtype: null, // 模板类型
                                ismust: 0, // 1必填 0非必填
                            },
                        ],
                        extendItemList: [
                            {
                                extendfieldname: '',// 扩展属性名称
                                fieldtype: null, // 模板类型
                                ismust: 0, // 1必填 0非必填
                            },
                        ]
                    }
                }
                this.dialogVisible = true;
            },
            handleCurrentChange(val) {
                this.query.currentPage = val;
                //scrollTo(0, 800);
                this.getList();
            },
            handleSizeChange(val) {
                this.query.currentPage = 1;
                this.query.pageSize = val;
                this.getList();
            },
            async getList() {
                this.listLoading = true
                let params = this.query
                let res = await queryAttributesTemplateList(params)
                // console.log(res)
                if (res.code === 0) {
                    this.list = res.data.list
                    this.totalNumber = res.data.totalNumber
                    this.listLoading = false
                } else {
                    this.$message.error(res.message)
                }
            },
        },
        created() {
            this.getList()
        }
    };
</script>

<style scoped>
    .head {
        display: flex;
        justify-content: flex-start;
    }

    .head p {
        min-width: 70px !important;
        line-height: 40px;
    }

    .el-title {
        font-weight: 600;
        line-height: 20px;
        padding-left: 5px;
    }
</style>
